package netWork;


import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//Udp客户端
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;
    //构造方法需要告诉服务器ip和端口号
    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        socket = new DatagramSocket();//这里为什么不用传端口号了
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner in = new Scanner(System.in);
        while(true){
            //输入你想发送的内容
            if(!in.hasNext()){
                break;
            }
            //把请求发给服务器需要构造DatagramPacket数据报,
            //构造时，还需要设置服务器Ip和端口号
            String request = in.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            //这里的InetAddress.getByName(serverIp)将字符串形式的服务器ip地址转换为InetAddress对象

            //发送数据报
            socket.send(requestPacket);
            //接受服务端响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //从服务器中读到的数据进行解析
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
